package org.microblog.service.impl;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.microblog.dao.FollowDao;
import org.microblog.dao.UserDao;
import org.microblog.entity.Follow;
import org.microblog.entity.User;
import org.microblog.service.FollowService;
import org.microblog.util.SessionFatoryUtil;

import java.sql.SQLException;
import java.util.List;

public class FollowServiceImpl implements FollowService {
    SqlSessionFactory sessionFactory = SessionFatoryUtil.sessionFactory;
    @Override
    public int getFollowedCount(int uId) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        int ret=dao.getFollowedCount(uId);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public int getFansCount(int uId) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        sqlSession.commit();
        int ret=dao.getFansCount(uId);
        sqlSession.close();
        return ret;
    }

    @Override
    public List<User> getFollowedByUidAndKeyword(int uId, String keyword) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        List<User> list=dao.getFollowedByUidAndKeyword(uId, keyword);
        sqlSession.commit();
        sqlSession.close();
        return list;
    }

    @Override
    public List<User> getFansByUidAndKeyword(int uId, String keyword) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        List<User> list=dao.getFansByUidAndKeyword(uId, keyword);
        sqlSession.commit();
        sqlSession.close();
        return list;
    }

    @Override
    public boolean isFollowed(int uId, int followedUid) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession(true);
        FollowDao followDao=sqlSession.getMapper(FollowDao.class);
        Boolean is=followDao.isFollowed(uId, followedUid);
        sqlSession.commit();
        sqlSession.close();
        return  is;
    }


    @Override
    public int addFollower(Follow follow) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        int ret=dao.addFollower(follow);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }

    @Override
    public int deleteFollower(Follow follow) throws SQLException {
        SqlSession sqlSession=sessionFactory.openSession();
        FollowDao dao=sqlSession.getMapper(FollowDao.class);
        int ret=dao.deleteFollower(follow);
        sqlSession.commit();
        sqlSession.close();
        return ret;
    }
}
